import Vue from 'vue'
import Vuex from 'vuex'
import { getSessionStorage, setSessionStorage, getLocalStorage, setLocalStorage } from '@/utils/storage'
import { addAsyncRoute, resetRouter } from '@/utils/router'
import { login, loginOut } from '@/api/login'
import { getVueRoutesByRole } from '@/api/menu'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 菜单折叠
    collapse: false,
    // 用户登陆信息
    superUserInfo: getSessionStorage('superUserInfo') || '',
    // 动态路由
    asyncRoute: getSessionStorage('asyncRoute') || [],
    // 吸顶标签组
    tags: [],
    // 主题色
    theme: getLocalStorage('theme') || 'light'
  },
  getters: {
    SUPER_USER_INFO: state => {
      return state.superUserInfo
    },
    ASYNC_ROUTE: state => {
      return state.asyncRoute
    },
    TAGS: state => {
      return state.tags
    },
    THEME: state => {
      return state.theme
    }
  },
  mutations: {
    SET_COLLAPSE: (state, collapse) => {
      state.collapse = collapse
    },
    SET_SUPER_USER_INFO: (state, superUserInfo) => {
      setSessionStorage('superUserInfo', superUserInfo)
      state.superUserInfo = superUserInfo
    },
    SET_ASYNC_ROUTE: (state, asyncRoute) => {
      setSessionStorage('asyncRoute', asyncRoute)
      state.asyncRoute = asyncRoute
    },
    ADDTAG: (state, tag) => {
      const checktag = state.tags.find(item => {
        return item.name === tag.name
      })
      if (!checktag) {
        state.tags.push(tag)
      }
    },
    DELTAG: (state, tagIndex) => {
      state.tags.splice(tagIndex, 1)
    },
    DELALLTAG: (state) => {
      state.tags = []
    },
    SET_THEME: (state, theme) => {
      setLocalStorage('theme', theme)
      state.theme = theme
    }
  },
  actions: {
    // 登陆
    login: async function ({ commit, getters }, loginForm) {
      const superUserInfo = await login(loginForm)
      if (superUserInfo) {
        commit('SET_SUPER_USER_INFO', superUserInfo)
        const asyncRoute = await getVueRoutesByRole()
        if (asyncRoute) {
          commit('SET_ASYNC_ROUTE', asyncRoute)
          addAsyncRoute('', getters.ASYNC_ROUTE)
          return true
        }
      }
    },
    // 退出登陆
    loginOut: async function ({ commit, getters }, loginForm) {
      const res = await loginOut()
      if (res) {
        commit('SET_SUPER_USER_INFO', null)
        commit('SET_ASYNC_ROUTE', null)
        resetRouter()
        return true
      }
    }
  },
  modules: {
  }
})
